﻿using Utilities;
using System.Linq;
using System.Text;
using System.Collections.Generic;

namespace Integration
{
    public class CsvSerializer<T> where T : class
    {
        public CsvSerializer()
        {
            TypeAccessor typeAccessor = typeof(T).GetTypeAccessor();
            _propertyAccessorsList = typeAccessor.PropertyAccessors.Values.ToList();
        }

        private StringBuilder _builder = new StringBuilder();
        private IList<PropertyAccessor> _propertyAccessorsList;

        public string Serialize(T instance)
        {
            _builder.Clear();

            _propertyAccessorsList.Join<PropertyAccessor>(
                _builder,
                ",",
                (builder, propertyAccessor, i) => 
            {
                string value = propertyAccessor.GetValue(instance).ToString();

                // Escape the quotes
                value = value.Replace(@"""", @"""""");

                if (value.Contains(",")
                    || value.Contains("\n")
                    || value.Contains("\r\n"))
                {
                    // Enclose with quotes
                    builder.Append('"');
                    builder.Append(value);
                    builder.Append('"');
                }
                else
                {
                    builder.Append(value);
                }
            });

            return _builder.ToString();
        }
    }
}
